<template>
    <n-drawer v-model:show="isDrawer" width="1000" :auto-focus="false" @after-leave="handleReset">
      <n-drawer-content title="文章管理" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="top"
          :label-width="100"
        >
          <n-form-item label="标题" path="title">
            <n-input
              placeholder="请输入标题"
              v-model:value="formParams.title"
            />
          </n-form-item>
          <n-form-item label="描述" path="description">
            <n-input placeholder="请输入描述" v-model:value="formParams.description" />
          </n-form-item>
          <n-form-item label="所属分类" path="category_id">
            <n-tree-select
              label-field="title"
              value-field="id"
              key-field="id"
              :options="getTreeList"
              clearable
              v-model:value="formParams.category_id"
              placeholder="请选择所属分类"
              @on-update:value="handleChangeCategory"

            />
          </n-form-item>
          <n-form-item label="上传图片" path="image">
            <BasicUpload
                :action="`${uploadUrl1}/api/common/cosupdate`"
                :width="100"
                :height="100"
                name="file"
                @uploadChange="changeSitePicture"
                :max="1"
                :maxSize="10"
                v-model:value="image"
                helpText="单个文件不超过10MB，最多只能上传1个文件"
            />
          </n-form-item>
          <n-form-item label="内容" path="content">
            <div class="editor-container">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
              />
              <Editor
                style="height: 350px; overflow-y: hidden"
                v-model="formParams.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
              />
            </div>
          </n-form-item>

        </n-form>
        <template #footer>
          <n-space>
            <n-button @click="handleReset">重置</n-button>
            <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </template>
  
  <script lang="ts" setup>
    import { onBeforeUnmount, ref, shallowRef, reactive, computed } from 'vue';
    import { useMessage, FormRules } from 'naive-ui';
    import { info,add,edit } from '@/api/article/index';
    import '@wangeditor/editor/dist/css/style.css'; // 引入 css
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
    import { useUserStoreWidthOut } from '@/store/modules/user';
    import { useGlobSetting } from '@/hooks/setting';
    const globSetting = useGlobSetting();
    const { uploadUrl, imgUrl } = globSetting;
    const uploadUrl1 = uploadUrl;
    const image = ref([]);

    const rules: FormRules = {
      title: {
        required: true,
        message: '标题不能为空',
        trigger: 'blur',
      }
    };

    const defaultValueRef = () => ({
      id: null,
      title: '',
      description: '',
      image: '',
      content: '',
      category_id: '',
    });

    const message = useMessage();
    const formRef: any = ref(null);
    const isDrawer = ref(false);
    const subLoading = ref(false);
    const formParams = ref(defaultValueRef());
    const emit = defineEmits(['change']);
    const userStore = useUserStoreWidthOut();
    const token = userStore.getToken;

    const props = defineProps({
      title: {
        type: String,
        default: '添加分类',
      },
      width: {
        type: Number,
        default: 450,
      },
      deptList: {
        type: Array,
      },
    });

    const getTreeList = computed(() => {
      return props.deptList;
    });

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    const mode = ref('default'); // 或 'simple'
    const uploadHeaders = reactive({
      Authorization: `Bearer ${token}`,
    });

    function handleChangeCategory(value){
      console.log(value);
    }

    // 内容 HTML
    const valueHtml = ref(formParams.value.content);

    type InsertFnType = (url: string, alt?: string, href?: string) => void;

    const toolbarConfig = {};
    const editorConfig = reactive({
      MENU_CONF: {
        uploadImage: {
          fieldName: 'file',
          headers: uploadHeaders,
          meta: {
            type: 0,
          },
          server: `${uploadUrl1}/api/common/cosupdate`,
          // 自定义插入图片
          customInsert(res: any, insertFn: InsertFnType) {
            // res 即服务端的返回结果
            // 从 res 中找到 url alt href ，然后插图图片
            if (res.code === 200) {
              insertFn(imgUrl + res.data.filePath);
            }
          },
        },
      },
      placeholder: '请输入内容...',
    });

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };
  
    async function openDrawer(id?) {
      if (id) {
        formParams.value.id = id;
        getInfo();
        return;
      }else{
        image.value = [];
      }
      isDrawer.value = true;
    }
  
    function closeDrawer() {
      isDrawer.value = false;
    }
  
    function formSubmit() {
      formParams.value.image = image.value[0];
      formRef.value.validate((errors) => {
        if (!errors) {
          const msg = formParams.value.id ? '编辑成功' : '添加成功';
          if (formParams.value.id) {
            edit(formParams.value).then((_) => {
              message.success(msg);
              emit('change');
              handleReset();
              closeDrawer();
            });
          } else {
            add(formParams.value).then((_) => {
              message.success(msg);
              emit('change');
              handleReset();
              closeDrawer();
            });
          }
        } else {
          message.error('请填写完整信息');
        }
      });
    }
  
    function handleReset() {
      formRef.value.restoreValidation();
      image.value = [];
      valueHtml.value = '';
      formParams.value = Object.assign(formParams.value, defaultValueRef());
    }
  
    function getInfo() {
      info({ id: formParams.value.id }).then((res) => {
        const params = {
          id: formParams.value.id,
          title: res.title,
          image: res.image,
          description: res.description,
          content: res.content,
          category_id: res.category_id,
        };

        if(res.image != null){
          image.value = res.image;
        }
        
        formParams.value = Object.assign(formParams.value, params);
        isDrawer.value = true;

        valueHtml.value = res.content;

      });
    }

    function changeSitePicture(file){
      image.value = file;
    }
  
    defineExpose({
      openDrawer,
      closeDrawer,
    });
  </script>
  